//
//  ACBaseWebViewController.m
//  ACFramework
//
//  Created by caoyq on 2017/7/29.
//

#import "ACBaseWebViewController.h"

@interface ACBaseWebViewController ()

@end

@implementation ACBaseWebViewController

#pragma mark - Life cycle

- (void)loadView {
    [super loadView];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;
    self.view = self.webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:self.urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    [self progressLayerInitialize];
    
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_progressLayer destory];
}

- (void)progressLayerInitialize {
    _progressLayer = [[ACWebProgressLayer alloc] init];
    _progressLayer.frame = CGRectMake(0, 42, [UIScreen mainScreen].bounds.size.width, 2);
    _progressLayer.progressColor = _progressColor;
    [self.navigationController.navigationBar.layer addSublayer:_progressLayer];
}

#pragma mark - setter

- (void)setProgressColor:(UIColor *)progressColor {
    if (progressColor != nil) {
        _progressColor = progressColor;
        _progressLayer.progressColor = _progressColor;
    }
}

#pragma mark - kvo

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    self.title = self.webView.title;
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title"];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self.progressLayer startLoad];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self.progressLayer finishedLoad];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [self.progressLayer finishedLoad];
}

@end
